﻿var Util = {};
(function(Util, $) {
    Util.ROOTPATH = "./";
    Util.Handler = {
        LoginPage: "Login.aspx"
    };
    Util.JsonResponseCode = {
        UNKOWN: 0,
        UNAUTHORIZED: 1,
        SUCCEED: 2,
        ERROR: 3
    };

    Util.ajax = function(options) {
        var overlay = null;
        if (options.autoOverlay) {
            overlay = $('<div class="ui-overlay-loading"></div>').appendTo(top.window.document.body || "body");
        }
        options.url = options.url || window.location.href.replace(/\?.*$/, "");
        return jQuery.ajax(jQuery.extend(true, {}, options, { dataType: "json",
            success: function(data, textStatus) {
                if (data == undefined || data == null) {
                    try {
                        console.error(options.url);
                    } catch (e) {
                    }
                    throw new Error("Ajax response null.");
                } else if (!data.Code) {
                    try {
                        console.error(data);
                    } catch (e) {
                    }
                    throw new Error("Incorrect json data.");
                }
                else if (data.Code == Util.JsonResponseCode.UNAUTHORIZED) {/* 需要登录（cookie超时） */
                    top.location.href = Util.ROOTPATH + Util.Handler.LoginPage;
                } else if (data.Code == Util.JsonResponseCode.SUCCEED) {
                    if (typeof options.success == "function")
                        options.success.call(this, data.Result, textStatus); //调用指定的成功处理函数
                } else if (data.Code == Util.JsonResponseCode.ERROR) {
                    if (typeof options.error == 'function')
                        options.error.call(this, data.Error, textStatus); //调用指定的错误处理函数
                } else {
                    throw new Error("Unknown json code: " + data.Code + ".");
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if (typeof options.error == 'function') {
                    options.error.call(this, errorThrown, textStatus);
                }
            }, complete: function(XMLHttpRequest, textStatus) {
                if (overlay) {
                    overlay.remove();
                }
                if (typeof options.complete == 'function') {
                    options.complete.call(this, XMLHttpRequest, textStatus);
                }
            }
        }));
    };
    //callback: funtion(succeed,data,error){};
    Util.post = function(url, data, callback, options) {
        return Util.ajax($.extend(true, {
            cache: false,
            success: function(result, textStatus) {
                if (typeof callback == "function") callback(true, result, null);
            },
            error: function(err, textStatus) {
                if (typeof callback == "function") callback(false, null, err);
            },
            url: url,
            data: data,
            type: 'POST'
        }, options));
    };
    //callback: funtion(succeed,data,error){};
    Util.get = function(url, data, callback, options) {
        return Util.ajax($.extend(true, {
            cache: false,
            success: function(result, textStatus) {
                if (typeof callback == "function") callback(true, result, null);
            },
            error: function(err, textStatus) {
                if (typeof callback == "function") callback(false, null, err);
            },
            url: url,
            data: data,
            type: 'GET'
        }, options));
    };

    Util.parseDateTime = function(dtString, dateformat) {
        if (!isNaN(dtString)) {
            return new Date(dtString - 0);
        }
        if (!dtString) {
            throw "Invalid dtString for ParseDateTime.";
        }
        //for JavaScriptSerializer.Serialize
        if (/\/Date\((\-?\d+)\)\//.test(dtString)) {
            return new Date(dtString.replace(/\/Date\((\-?\d+)\)\//, "$1") - 0);
        }
        dateformat = dateformat || "yyyy-MM-dd";
        //"2012-10-24 12:11:10.999".match(reg)
        //["2012-10-24 12:11:10.999", "2012", "10", "24", " 12:11:10.999", "12", "11", "10", ".999", "999"]
        var reg = /(\d+)[\/\-](\d+)[\/\-](\d+)( (\d+)\:(\d+)\:(\d+)(\.(\d+))*)*/;
        var m = dtString.match(reg);
        if (m) {
            var dt = null;
            var year, month, date;
            if (/[y]+[\/\-][m]+[\/\-][d]+/i.test(dateformat)) {/* yyyy-MM-dd */
                year = m[1];
                month = m[2];
                date = m[3];
            } else if (/[m]+[\/\-][d]+[\/\-][y]+/i.test(dateformat)) {/* MM/dd/yyyy */
                year = m[3];
                month = m[1];
                date = m[2];
            } else if (/[d]+[\/\-][m]+[\/\-][y]+/i.test(dateformat)) {/* dd/MM/yyyy */
                year = m[3];
                month = m[2];
                date = m[1];
            } else {
                throw "Invalid dateformat for ParseDateTime.";
            }
            if (year && month < 13 && date < 32) {
                dt = new Date(year - 0, month - 1, date - 0);
            } else {
                throw "Invalid dtString for ParseDateTime.";
            }
            if (dt) {
                if (m[4]) {
                    dt.setHours(m[5] - 0);
                    dt.setMinutes(m[6] - 0);
                    dt.setSeconds(m[7] - 0);
                }
                if (m[8]) {
                    dt.setMilliseconds(m[9].replace(/^(\d{1,3})(\d*)/, "$1") - 0);
                }
            }
            return dt;
        }
        throw "Invalid dtString for ParseDateTime.";
    };
    Util.getTimeString = function(dt, ignoreMilliseconds) {
        if (dt.valueOf() <= -62135596800000) {
            return null;
        }
        var y = dt.getFullYear(), M = dt.getMonth() + 1, d = dt.getDate(), h = dt.getHours(), m = dt.getMinutes(), s = dt.getSeconds(), f = dt.getMilliseconds()
        return [y, M < 10 ? "0" + M : M, d < 10 ? "0" + d : d].join("-") + " " + [h < 10 ? "0" + h : h, m < 10 ? "0" + m : m, s < 10 ? "0" + s : s].join(":") + (ignoreMilliseconds ? "" : ("." + f));
    };
    Util.getDateString = function(dt, format) {
        if (dt.valueOf() <= -62135596800000) {
            return null;
        }
        var y = dt.getFullYear(), M = dt.getMonth() + 1, d = dt.getDate();
        return [y, M < 10 ? "0" + M : M, d < 10 ? "0" + d : d].join("-");
    };
    Util.getFormData = function(form) {
        if (form && form.elements) {
            var result = {};
            $.each(form.elements, function(index, elem) {
                if (elem.name) {
                    var skip = false;
                    var v = elem.value;
                    switch (elem.type) {
                        case "checkbox":
                            skip = !elem.checked;
                            break;
                        case "radio":
                            skip = !elem.checked;
                            break;
                        case "button": break;
                        case "file": break;
                        case "hidden": break;
                        case "password": break;
                        case "reset": break;
                        case "select-one": break;
                        case "select-multiple": break;
                        case "submit": break;
                        case "text": break;
                        case "textarea": break;
                    }
                    if (!skip) {
                        if (result[elem.name]) {
                            result[elem.name].push(v);
                        } else {
                            result[elem.name] = [v];
                        }
                    }
                }
            });
            return result;
        }
        return null;
    };
    Util.setFields = function(element, data) {
        data = data || {};
        $(element).find('[field]').each(function(index, elem) {
            elem = $(elem);
            var v = data[elem.attr('field')];
            if (v == null || typeof v == "undefined")
                v = "";
            elem.val(v);
        });
    },
    Util.getFields = function(element) {
        var obj = {};
        $(element).find('[field]').each(function(index, elem) {
            elem = $(elem);
            obj[elem.attr('field')] = elem.val();
        });
        return obj;
    };
    Util.openWindow = function(url, width, height, features, name) {
        var f = $.extend(true, { width: width, height: height, left: (window.screen.width - width) / 2, top: Math.min(30, (window.screen.height - height) / 2) }, features);
        var arr = []; ;
        for (var k in f) {
            arr.push(k + "=" + f[k]);
        }
        window.open(url, name || "popwinow", arr.join(","));
    };
    Util.String = {
        trim: function(oldstr) {
            if (oldstr)
                return oldstr.replace(/(^\s\s*)|(\s*\s)/ig, '');
            return oldstr;
        },
        trimStart: function(oldstr) {
            if (oldstr)
                return oldstr.replace(/(^\s\s*)/ig, '');
            return oldstr;
        },
        trimEnd: function(oldstr) {
            if (oldstr)
                return oldstr.replace(/(\s*\s)/ig, '');
            return oldstr;
        }
    };
    Util.loadObjects = function(elem, key) {
        var container = {};
        $.each(eval("(" + $(elem)[0].innerHTML + ")"), function() {
            container[this[key]] = this;
        });
        return container;
    };
})(Util, jQuery);